<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <el-form status-icon :model="pass" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input show-password type="password" v-model="pass.old_pwd"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input show-password type="password" v-model="pass.new_pwd"></el-input>
      </el-form-item>
      <el-form-item label="请再次密码" prop="re_pwd">
        <el-input show-password type="password" v-model="pass.re_pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fn">确认修改</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { PatchPsaa } from '@/api/user'
export default {
  data() {
    const newPwd = (rule, value, callback) => {
      if (value === this.pass.old_pwd) {
        callback(new Error('两次输入密码不能一致!'))
      } else {
        callback()
      }
    }
    const rePwd = (rule, value, callback) => {
      if (value === this.pass.new_pwd) {
        callback()
      } else {
        callback(new Error('两次输入密码不一致!'))
      }
    }
    return {
      pass: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rules: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6 到 15 个字符', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6 到 15 个字符', trigger: 'blur' },
          { validator: newPwd, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6 到 15 个字符', trigger: 'blur' },
          { validator: rePwd, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    fn() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // console.log('通过了')
        const { data: res } = await PatchPsaa(this.pass)
        // console.log(res)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.$refs.form.resetFields()
          this.$store.commit('user/updataToken', '')
          this.$store.commit('user/updateUser', {})
          this.$router.push('/login')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    reset() {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 400px;
}
</style>
